package com.coolwen.util;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by user on 2016/6/5.
 */
public class LimitRetryHashedMatcher extends HashedCredentialsMatcher {

//     Logger logger = Logger.getLogger(getClass());

    /**
     * JavaBeans-compatibile no-arg constructor intended for use in IoC/Dependency Injection environments.  If you
     * use this constructor, you <em>MUST</em> also additionally set the
     * {@link #setHashAlgorithmName(String) hashAlgorithmName} property.
     */
//    public LimitRetryHashedMatcher() {
//        logger.info("查找结果doCredentialsMatch");
//    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        String username = (String) token.getPrincipal();
//        logger.info(JSON.toJSON("查找结果"+username));
//        System.out.println("登录用户名:"+username);
//retrycount + 1
        Object element = EhcacheUtil.getItem(username);
        if (element == null) {
            EhcacheUtil.putItem(username, 1);
            element=0;
        }else{
            int count=Integer.parseInt(element.toString())+1;
            element=count;
            EhcacheUtil.putItem(username,element);
        }
        AtomicInteger retryCount = new AtomicInteger(Integer.parseInt(element.toString()));
        if (retryCount.incrementAndGet() > 5) {
//if retrycount >5 throw
            throw new ExcessiveAttemptsException();
        }
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
//clear retrycount
            EhcacheUtil.removeItem(username);
        }
        return matches;
    }
}
